package com.jeeplus.test.jlnu.admissionInfo.service.impl;

import com.alibaba.fastjson.JSON;
import com.jeeplus.test.jlnu.admissionInfo.domain.entity.AdmissionInfo;
import com.jeeplus.test.jlnu.admissionInfo.domain.entity.ImportFailLog;
import com.jeeplus.test.jlnu.admissionInfo.mapper.AdmissionInfoMapper;
import com.jeeplus.test.jlnu.admissionInfo.mapper.ExcelMapper;
import com.jeeplus.test.jlnu.admissionInfo.service.AdmissionInfoService;
import com.jeeplus.test.jlnu.admissionInfo.service.ExcelServiceDean;
import com.jeeplus.test.jlnu.admissionInfo.utils.MyWebSocketHandler;
import com.jeeplus.test.jlnu.admissionInfo.utils.VerifyExcel;
import com.jeeplus.test.jlnu.archivalInfo.domain.entity.ArchivalInfo;
import com.jeeplus.test.jlnu.changeStuInfo.domain.entity.ChangeStuInfo;
import com.jeeplus.test.jlnu.changeStuInfo.mapper.ChangeStuInfoMapper;
import com.jeeplus.test.jlnu.deanOffice.domain.entity.JlnuDeansOffice;
import com.jeeplus.test.jlnu.deanOffice.mapper.DeansOfficeMapper;
import com.jeeplus.test.jlnu.graduationInfo.domain.entity.NewGraduationInfo;
import com.jeeplus.test.jlnu.student.domain.entity.BsssStudentInfo;
import com.jeeplus.test.jlnu.xlsxManage.service.JlnuXlsxManageService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class ExcelServiceDeanImpl implements ExcelServiceDean {
    @Autowired
    private DeansOfficeMapper deansOfficeMapper;
    @Autowired
    private ExcelMapper excelMapper;
    @Autowired
    private MyWebSocketHandler webSocketHandler;
    @Autowired
    private ChangeStuInfoMapper changeStuInfoMapper;

    @Autowired
    private AdmissionInfoMapper admissionInfoMapper;
    @Autowired
    private JlnuXlsxManageService jlnuXlsxManageService;

    @Autowired
    private AdmissionInfoService admissionInfoService;


    @Override
    public void insertDataDean(List<JlnuDeansOffice> dataList, String officeId, String importType, String templateInfoType,
                               int templateId) {

        try {
            //判断Excel是否有数据
            if (CollectionUtils.isEmpty(dataList)) {
                return;
            }
            //需要导入的数据集合
            List<JlnuDeansOffice> newDataList = new ArrayList<>();

            //判断Excel中是否有重复的数据
            Map repeatParam = new HashMap();

            //错误数据集合
            List<String> errorList = new ArrayList();
            List<Map<String, Object>> finalContent = VerifyExcel.getTemplateContent(jlnuXlsxManageService, templateId);

            AtomicInteger i = new AtomicInteger();
            dataList.forEach(e -> {

                i.getAndIncrement();
                VerifyExcel.validateObjectFields(e, finalContent, errorList,i);
                e.setStudentid(e.getXh());
                String type = null;
                String suffix = null;
                if (!StringUtils.isEmpty(e.getXh())) {
                    type = "xh";
                    suffix = e.getXh();
                } else if (!StringUtils.isEmpty(e.getZkzh())) {
                    type = "zkzh";
                    suffix = e.getZkzh();
                } else if (!StringUtils.isEmpty(e.getKsh())) {
                    type = "ksh";
                    suffix = e.getKsh();
                }

                if (StringUtils.isEmpty(suffix)) {
                    //学号、考生号、准考证号都为空则不可导入
                    String msg = "第"+i+"行 "+ " 姓名：" + e.getXm() + "学号为空";
                    errorList.add(msg);
                    return;
                }
                if(!errorList.isEmpty()){
                    return;
                }

                if (suffix != null) {
                    repeatParam.put("XH" + suffix, System.currentTimeMillis());

                    //如果是通过数据管理中导入的Excel数据就只覆盖重复的jlnu_deans_office主表数据
                    if (importType.equals("DBMS")) {
                        List<Integer> ids = deansOfficeMapper.selectAdmissionInfo(type, suffix);
                        if (!CollectionUtils.isEmpty(ids)) {
                            //数据库中有相同的数据则覆盖
                            AdmissionInfo admissionInfo = new AdmissionInfo();
                            admissionInfo.setStudentId(e.getXh());
                            admissionInfo.setExamineeNum(e.getKsh());
                            admissionInfo.setAdmissionNum(e.getZkzh());//准考证号
                            admissionInfo.setName(e.getXm());//姓名
                            admissionInfo.setGender(e.getXbmc());//性别
                            admissionInfo.setPoliticalOutlook(e.getZzmmmc());//政治面貌
                            admissionInfo.setNation(e.getMzmc());//民族
                            admissionInfo.setTransferState(1);
                            admissionInfo.setGradation(e.getZycc());//层次
                            admissionInfo.setYear(e.getNf()); //年度
                            admissionInfo.setIdCard(e.getSfzh());//身份证号
                            admissionInfo.setAdmissionAcademy(e.getLqxy());//录取学院
                            admissionInfo.setAdmissionMajor(e.getZymc());//录取专业
                            admissionInfo.setEducationalSystem(e.getZyxz());//学制
                            admissionInfo.setExamineeSort(e.getKslbmc());//考生类别
                            admissionInfo.setHomeAddress(e.getJtdz());//家庭（邮寄）地址
                            admissionInfo.setFlag(BsssStudentInfo.UNDERGRADUATE); //本科生
                            admissionInfoMapper.batchUpdateeAdmissionInfoById(ids, admissionInfo);
                        } else {
                            newDataList.add(e);
                        }
                        //如果是通过录取管理中导入的Excel数据就只覆盖重复的jlnu_admission_info主表数据
                    } else {
                        List<Integer> ids = deansOfficeMapper.selectJlnuDeansOffice(type, suffix, e.getSfzh());
                        if (!CollectionUtils.isEmpty(ids)) {
                            //数据库中有相同的数据则覆盖
                            deansOfficeMapper.batchUpdateDeansOffice(ids, e);
                        } else {
                            boolean add = newDataList.add(e);
                        }
                    }


                }
            });

            if (!CollectionUtils.isEmpty(errorList)) {
                sendMsg(errorList);
                //存储到数据库
                ImportFailLog param = new ImportFailLog();
                param.setTemplateId(templateId);
                param.setMessage(JSON.toJSONString(errorList));
                param.setImportType("1");
                admissionInfoService.importLogAdd(param);
            }

            if (!CollectionUtils.isEmpty(newDataList)) {
                List<AdmissionInfo> admissionInfos = copyAdmissionInfos(newDataList, importType);
                List<NewGraduationInfo> graduationInfos = copyGraduationInfos(newDataList, importType);
                List<ArchivalInfo> archivalInfos = copyArchivalInfoInfos(newDataList, importType);
                // 使用 Stream 生成新列表
                List<JlnuDeansOffice> jlnuDeansOffice = newDataList.stream()
                        .map(e -> {
                            e.setStudentid(e.getXh());
                            e.setOfficeId(officeId);
                            return e; // 返回生成的 AdmissionInfo 对象
                        }).collect(Collectors.toList());// 收集到 admissionInfos 列表中
                //向学籍信息中同步数据
                List<ChangeStuInfo> changeStuInfos = newDataList.stream()
                        .map(e -> {
                            ChangeStuInfo csi = new ChangeStuInfo();
                            csi.setStudentId(e.getXh());
                            csi.setOfficeId(officeId);
                            csi.setSource("1");
                            csi.setCreateTime(new Date());
                            csi.setKsh(e.getKsh());
                            csi.setName(e.getXm());
                            csi.setApproveState(0);
                            csi.setYear(e.getNf());
                            csi.setTransferState(1);
//                        csi.setSchoolYear(e.getNf());
                            csi.setCollegeName(e.getLqxy());
                            csi.setMajorName(e.getZymc());
                            csi.setExamTicketNumber(e.getZkzh());
                            csi.setBirthDate(e.getCsny());
                            csi.setGender(e.getXbmc());
                            csi.setEthnicity(e.getMzmc());
                            csi.setPoliticalStatus(e.getZzmmmc());
                            csi.setIdCardNumber(e.getSfzh());
                            csi.setEducationLevel(e.getZycc());
                            csi.setAcademicSystem(e.getZyxz());
                            csi.setStudentSource(e.getLydq());
                            csi.setAreaCode(e.getYzbm());
                            return csi; // 返回生成的 AdmissionInfo 对象
                        }).collect(Collectors.toList());// 收集到 admissionInfos 列表中

                changeStuInfoMapper.insertChangeStu(changeStuInfos);//学籍管理循环插入
                deansOfficeMapper.saveDeansOffice(jlnuDeansOffice);
                // 插入录取信息表全部数据
                excelMapper.saveFirstData(admissionInfos);

//                // 插入学籍信息表（只插入学号）
//                excelMapper.saveSecondData(admissionInfos);
//
//                // 插入毕业信息表（只插入学号）
//                excelMapper.saveThirdData(graduationInfos);

                // 插入就业信息表（只插入学号）
//            excelMapper.saveFourth(admissionInfos);

                // 插入学位信息表（只插入学号）//暂时没用上
//                excelMapper.saveFifth(admissionInfos);
//
//                // 插入学历信息表（只插入学号） //暂时没用上
//                excelMapper.saveSixth(admissionInfos);
//
//                // 插入转递（邮寄信息表）
////            excelMapper.saveSeventh(admissionInfos);
//                // 档案信息表
//                excelMapper.saveEighth(archivalInfos);

                //往学生端插入学号数据
                // 创建两个列表来存储不同 flag 的对象
//            excelMapper.saveFourteenth(admissionInfos);
//            excelMapper.saveFifteenth(admissionInfos);

                List<AdmissionInfo> otherFlagList = new ArrayList<>();

                for (AdmissionInfo admissionInfo : admissionInfos) {
                    otherFlagList.add(admissionInfo);
                }
                excelMapper.saveTwelfth(otherFlagList);

            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            sendMsg("数据异常，请联系管理员" + e.getMessage().toString());
        }
    }

    private void sendMsg(List<String> msg) {
        try {
            //
            webSocketHandler.sendMsgList(msg);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

    private void sendMsg(String msg) {
        try {
            //
            webSocketHandler.sendMsg(msg);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

    //录取信息表字段赋值
    private List<AdmissionInfo> copyAdmissionInfos(List<JlnuDeansOffice> admissionInfoList, String importType) {
        List<AdmissionInfo> admissionInfos = admissionInfoList.stream()
                .map(StudentInfoEntity -> {
                    AdmissionInfo admissionInfo = new AdmissionInfo();
                    admissionInfo.setOfficeId(StudentInfoEntity.getOfficeId());
                    admissionInfo.setStudentId(StudentInfoEntity.getXh());
                    admissionInfo.setRecordType("1"); //表示教务处
                    if (importType.equals("DBMS")) {
                        admissionInfo.setApproveState(1);//审批状态待提交
                    } else {
                        admissionInfo.setApproveState(3);//审批状态通过
                    }
                    admissionInfo.setTransferState(1);
                    admissionInfo.setExamineeNum(StudentInfoEntity.getKsh());
                    admissionInfo.setAdmissionNum(StudentInfoEntity.getZkzh());//准考证号
                    admissionInfo.setName(StudentInfoEntity.getXm());//姓名
                    admissionInfo.setGender(StudentInfoEntity.getXbmc());//性别
                    admissionInfo.setPoliticalOutlook(StudentInfoEntity.getZzmmmc());//政治面貌
                    admissionInfo.setIdCard(StudentInfoEntity.getSfzh());//身份证号
                    // 设置录取学校为吉林师范大学
                    admissionInfo.setAdmissionSchools("吉林师范大学");//录取学校
                    admissionInfo.setOfficeId(StudentInfoEntity.getOfficeId());
                    admissionInfo.setAdmissionAcademy(StudentInfoEntity.getLqxy());//录取学院
                    admissionInfo.setAdmissionMajor(StudentInfoEntity.getZymc());//录取专业
                    admissionInfo.setEducationalSystem(StudentInfoEntity.getZyxz());//学制
                    admissionInfo.setExamineeSort(StudentInfoEntity.getKslbmc());//考生类别
                    admissionInfo.setHomeAddress(StudentInfoEntity.getJtdz());//家庭（邮寄）地址
                    admissionInfo.setFlag(BsssStudentInfo.UNDERGRADUATE); //本科生
                    admissionInfo.setNation(StudentInfoEntity.getMzmc());//民族
                    admissionInfo.setGradation(StudentInfoEntity.getZycc());//层次
                    admissionInfo.setYear(StudentInfoEntity.getNf()); //年度
                    return admissionInfo; // 返回生成的 AdmissionInfo 对象
                }).collect(Collectors.toList()); // 收集到 admissionInfos 列表中
        return admissionInfos;
    }


    //毕业信息表字段赋值
    private List<NewGraduationInfo> copyGraduationInfos(List<JlnuDeansOffice> admissionInfoList, String importType) {
        List<NewGraduationInfo> graduationInfos = admissionInfoList.stream()
                .map(StudentInfoEntity -> {

                    NewGraduationInfo newGraduationInfo = new NewGraduationInfo();
                    newGraduationInfo.setOfficeId(StudentInfoEntity.getOfficeId());
                    newGraduationInfo.setStudentId(StudentInfoEntity.getXh());

                    newGraduationInfo.setExamineeNum(StudentInfoEntity.getKsh());
                    newGraduationInfo.setAdmissionNum(StudentInfoEntity.getZkzh());//准考证号
                    newGraduationInfo.setName(StudentInfoEntity.getXm());
                    newGraduationInfo.setGender(StudentInfoEntity.getXbmc());

//                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//                    try {
//                        Date birthday = dateFormat.parse(StudentInfoEntity.getCsny());
//                        newGraduationInfo.setBirthday(birthday);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }

                    newGraduationInfo.setPoliticalOutlook(StudentInfoEntity.getZzmmmc());
                    newGraduationInfo.setNation(StudentInfoEntity.getMzmc());
                    newGraduationInfo.setIdCard(StudentInfoEntity.getSfzh());
                    newGraduationInfo.setMajorName(StudentInfoEntity.getZymc());
                    newGraduationInfo.setEducationalSystem(StudentInfoEntity.getZyxz());
                    newGraduationInfo.setGradation(StudentInfoEntity.getZycc());
                    newGraduationInfo.setTransferState(1);
                    newGraduationInfo.setEnrollmentDate(StudentInfoEntity.getAdmissionDate());
                    newGraduationInfo.setCollegeName(StudentInfoEntity.getLqxy());
                    newGraduationInfo.setGrade(StudentInfoEntity.getGrade());
                    newGraduationInfo.setYear(StudentInfoEntity.getNf());
                    newGraduationInfo.setTransferState(1);

                    return newGraduationInfo; // 返回生成的 AdmissionInfo 对象
                }).collect(Collectors.toList()); // 收集到 admissionInfos 列表中
        return graduationInfos;
    }

    //档案信息表字段赋值
    private List<ArchivalInfo> copyArchivalInfoInfos(List<JlnuDeansOffice> admissionInfoList, String importType) {
        List<ArchivalInfo> archivalInfos = admissionInfoList.stream()
                .map(StudentInfoEntity -> {
                    ArchivalInfo archivalInfo = new ArchivalInfo();
                    archivalInfo.setGrade(StudentInfoEntity.getGrade());
                    archivalInfo.setName(StudentInfoEntity.getXm());
                    archivalInfo.setTransferState(1);
                    archivalInfo.setCollegeName(StudentInfoEntity.getLqxy());
                    archivalInfo.setAdmissionMajor(StudentInfoEntity.getZymc());
                    archivalInfo.setOfficeId(StudentInfoEntity.getOfficeId());
                    archivalInfo.setStudentId(StudentInfoEntity.getXh());
                    archivalInfo.setCandidateNumber(StudentInfoEntity.getKsh());
                    archivalInfo.setAdmissionTicketNumber(StudentInfoEntity.getZkzh());//准考证号
                    archivalInfo.setGender(StudentInfoEntity.getXbmc());
                    archivalInfo.setEthnicity(StudentInfoEntity.getMzmc());
                    archivalInfo.setIdNumber(StudentInfoEntity.getSfzh());
                    archivalInfo.setGradation(StudentInfoEntity.getZycc());
                    archivalInfo.setYear(StudentInfoEntity.getNf());
                    archivalInfo.setMajorName(StudentInfoEntity.getZymc());

                    archivalInfo.setTransferState(1);
                    return archivalInfo;
                }).collect(Collectors.toList());
        return archivalInfos;
    }


}

